package listener;

import java.io.IOException;

import java.lang.reflect.Field;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.core.io.support.PropertiesLoaderUtils;

import util.ConfigUtil;
import util.OssUtil;
import util.PushUtil;
import util.WeixinUtil;

/**
 * 由老夫一手创建类!  2018 06 05 
 * web监听器配置环境
 * @author NR
 */

public class WebContextListener implements ServletContextListener{

	public static String env_code = null;
	
	private static Properties props = null;
	
	/**
	 * 需要配置环境的类
	 */
	private static Class[] envClassList = {OssUtil.class,ConfigUtil.class,WeixinUtil.class,PushUtil.class};
	
	static{
		try {
			props = PropertiesLoaderUtils.loadAllProperties("config.properties");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void contextInitialized(ServletContextEvent sce) {
		
		String env = sce.getServletContext().getInitParameter("spring.profiles.active");
		env_code = env;
		switch(env){
		case "dev":System.out.println("测试环境启动");
			break;
		case "pe":System.out.println("正式环境启动");
			break;
		}
		for (Class obj:envClassList) {
			dealEnv(obj);
		}
	}

	public void contextDestroyed(ServletContextEvent sce) {
		
	}
	
	/**
	 * 极其简单的反射应用(用于切换dev pe 环境)
	 * @param T
	 */
	public void dealEnv(Class T){
		Field[] fileds = T.getDeclaredFields();
		for (Field field :fileds) {
			if(props.containsKey(field.getName()+"_"+WebContextListener.env_code.toUpperCase())){
				try{
					field.set(T, props.get(field.getName()+"_"+WebContextListener.env_code.toUpperCase()));
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
}